<template>
   <!-- 头部部分 -->
    <el-page-header :icon="Fold" back-text="日志">
        <template #content>
        <span class="text-large font-600 mr-3"> 首页&nbsp;/ 运营 /</span>
        </template>
        <div class="right">
            <el-avatar :icon="UserFilled" />
            <span>15210418591</span>
        </div>
        <div class="white"></div>
    </el-page-header>
    
    <!-- 输入框 -->
    <div class="search">
         <el-button type="danger" :icon="Plus" style="margin-left:1187px;position: absolute;margin-top: 56px;
        transform: scale(1);" @click="handleAdd">添加</el-button>
          <el-button type="info" :icon="Refresh" style="margin-left: 1268px;border-radius: 8px;margin-top:57px; 
          transform: scale(1);" @click="handleRefresh">刷新</el-button>
    </div>
    
    <!-- table表格 -->
    <table class="log-table">
        <thead>
            <tr>
            <th>标题</th>
            <th>图片</th>
            <th>是否显示</th>
            <th>添加日期</th>
            <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="item in tableData" :key="item.id">
            <td>{{ item.title }}</td>
            <td>
                 <img :src="getImageUrl(item.image)" alt="图片" style="width: 127px; height: 75px;" />
            </td>
            <td>{{ item.display === 1 ? '是' : '否' }}</td>
            <td>{{ item.createAt }}</td>
            <td>
                <el-button type="primary" @click="handleEdit(item)">编辑</el-button>
            </td>
            </tr>
        </tbody>
    </table>
    
    <!-- 分页区域 -->
    <div class="footer">
        <span>共{{ total }}条</span>
        <div class="flex flex-wrap items-center">
            <el-select v-model="pageSize" @change="handleSizeChange" style="width: 120px; margin-right: 10px;">
                <el-option label="5条/页" :value="5" />
                <el-option label="10条/页" :value="10" />
                <el-option label="15条/页" :value="15" />
            </el-select>
        </div>
        <el-pagination
            background
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
        />
        <div style="display: flex; align-items: center; margin-left: 10px;">
            前往
            <el-input 
                v-model="jumpPage" 
                style="width: 50px; margin: 0 5px;" 
                @keyup.enter="handleJumpPage"
                @blur="handleJumpPage"
            />
            页
        </div>
    </div>
    
    <!-- 添加/编辑模态框 -->
    <el-dialog :title="isEdit ? '编辑' : '添加'" v-model="dialogVisible" width="50%">
        <el-form :model="form" label-width="80px" ref="formRef">
            <el-form-item label="标题" required prop="title">
                <el-input v-model="form.title" />
            </el-form-item>
            <el-form-item label="图片" required>
                <el-upload
                    class="upload-demo"
                    action=""
                    :auto-upload="false"
                    :on-change="handleFileChange" 
                    :file-list="fileList"
                    :on-remove="handleRemove"
                    accept="image/*"
                >
                    <div v-if="fileList.length === 0" class="upload-plus">
                        <el-icon class="plus-icon"><Plus /></el-icon>
                        <div class="plus-text">点击上传</div>
                    </div>
                    <div v-else class="uploaded-image">
                        <img :src="fileList[0].url" class="uploaded-img" />
                        <el-icon class="remove-icon"><Delete /></el-icon>
                    </div>
                </el-upload>
            </el-form-item>
            <el-form-item label="应用设备">
                <el-radio-group v-model="form.applyType">
                    <el-radio label="0">全部设备</el-radio>
                    <el-radio label="1">应用部分设备</el-radio>
                    <el-radio label="2">屏蔽部分设备</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item 
                label="选择设备" 
                v-if="form.applyType === '1' || form.applyType === '2'" 
                required
            >
                <el-checkbox-group v-model="form.equipmentIds">
                    <el-checkbox label="1">设备1</el-checkbox>
                    <el-checkbox label="2">设备2</el-checkbox>
                    <el-checkbox label="3">设备3</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="是否显示">
                <el-radio-group v-model="form.display">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Fold, Refresh, UserFilled, Plus, Delete } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { getProhibitList, getProhibitUpdate, getProhibitChange, getProhibitPoints, 
    getProhibitRoad } from '@/components/api/Prohibit';

const value = ref(false);
const fileList = ref([]);
const selectedFile = ref(null);
const formRef = ref(null);
const isEdit = ref(false);

// 分页相关数据
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const jumpPage = ref(1);

const tableData = ref([]);

// 获取图片完整URL
const getImageUrl = (imagePath) => {
    if (!imagePath) return '默认图片路径';
    if (imagePath.startsWith('http')) return imagePath;
    return `http://106.13.143.56:8080/garbageSys/images${imagePath}`;
};

// 获取严禁投递列表
const getDrawalListFun = () => {
    const drawalListData = {
        pageIndex: currentPage.value,
        pageSize: pageSize.value,
    }
    getProhibitList(drawalListData)
    .then(res => {
        if(res.code == 200){
            tableData.value = res.dataset.list || [];
            total.value = res.dataset.total || 0;
            
            // 更新跳转页码为当前页
            jumpPage.value = currentPage.value;
        } else {
            tableData.value = [];
            total.value = 0;
            ElMessage.warning(res.msg || '暂无数据');
        }
    })
    .catch(err => {
        console.error('获取列表失败:', err);
        ElMessage.error('获取列表失败');
    });
}

// 刷新函数
const handleRefresh = () => {
    getDrawalListFun();
    ElMessage.success('数据已刷新');
}

// 上传图片
const uploadImage = async () => {
    try {
        const formData = new FormData();
        formData.append('file', selectedFile.value);
        
        const res = await getProhibitRoad(formData);
        console.log('上传图片返回:', res);
        
        if (res.code === 200) {
            let imagePath = res.dataset.filePath || res.dataset;
            if (imagePath && !imagePath.startsWith('http')) {
                imagePath = `http://106.13.143.56:8080/garbageSys/images${imagePath}`;
            }
            return { code: 200, dataset: { imagePath } };
        } else {
            ElMessage.error(res.msg || '图片上传失败');
            return { code: -1 };
        }
    } catch (err) {
        console.error('上传图片失败:', err);
        ElMessage.error('图片上传失败');
        return { code: -1 };
    }
};

// 模态框
const dialogVisible = ref(false);
const form = reactive({
    title: '',
    image: '',
    display: '0',
    equipmentIds: [],
    applyType: '0',
    id: ''
});

// 添加按钮点击事件
const handleAdd = () => {
    isEdit.value = false;
    resetForm();
    dialogVisible.value = true;
}

// 编辑按钮点击事件
const handleEdit = (item) => {
    isEdit.value = true;
    // 填充表单数据
    Object.assign(form, {
        title: item.title,
        image: item.image,
        display: item.display?.toString() || '0',
        applyType: item.applyType?.toString() || '0',
        equipmentIds: item.equipmentIds || [],
        id: item.id
    });
    
    // 设置文件列表显示
    if (item.image) {
        fileList.value = [{
            name: '当前图片',
            url: getImageUrl(item.image)
        }];
    } else {
        fileList.value = [];
    }
    
    dialogVisible.value = true;
}

// 提交表单
const submitForm = async () => {
    // 表单验证
    if (!form.title) {
        ElMessage.error('请输入标题');
        return;
    }
    if (!selectedFile.value && !form.image) {
        ElMessage.error('请先上传图片');
        return;
    }
    if (!form.display) {
        ElMessage.error('请选择是否显示');
        return;
    }
    if (['1', '2'].includes(form.applyType) && form.equipmentIds.length === 0) {
        ElMessage.error('请选择设备');
        return;
    }

    try {
        let imageUrl = form.image;
        
        // 先上传图片
        if (selectedFile.value) {
            const uploadRes = await uploadImage();
            if (uploadRes.code === 200 && uploadRes.dataset.imagePath) {
                imageUrl = uploadRes.dataset.imagePath;
            } else {
                return;
            }
        }

        // 准备请求数据
        const requestData = {
            title: form.title, 
            image: imageUrl,
            display: form.display,
            applyType: form.applyType,
            equipmentIds: form.equipmentIds
        };

        // 如果是编辑模式，添加id
        if (isEdit.value) {
            requestData.id = form.id;
        }

        console.log("请求数据:", requestData);

        let res;
        if (isEdit.value) {
            // 编辑接口
            res = await getProhibitChange(requestData);
        } else {
            // 新增接口
            res = await getProhibitPoints(requestData);
        }

        if (res.code === 200) {
            ElMessage.success(isEdit.value ? '编辑成功' : '添加成功');
            dialogVisible.value = false;
            // 重新获取列表数据
            getDrawalListFun();
            resetForm();
        } else {
            ElMessage.error(res.msg || (isEdit.value ? '编辑失败' : '添加失败'));
        }
    } catch (err) {
        console.error('操作失败:', err);
        ElMessage.error('网络错误');
    }
};

// 重置表单
const resetForm = () => {
    form.title = '';
    form.image = '';
    form.display = '0';
    form.applyType = '0';
    form.equipmentIds = [];
    form.id = '';
    fileList.value = [];
    selectedFile.value = null;
};

// 文件选择处理
const handleFileChange = (file, files) => {
    selectedFile.value = file.raw;
    fileList.value = [file];
    
    // 预览图片
    const reader = new FileReader();
    reader.onload = (e) => {
        file.url = e.target.result;
    };
    reader.readAsDataURL(file.raw);
};

// 文件移除处理
const handleRemove = () => {
    fileList.value = [];
    selectedFile.value = null;
    form.image = '';
};

// 分页相关方法
// 页码改变
const handleCurrentChange = (val) => {
    currentPage.value = val;
    getDrawalListFun();
}

// 每页条数改变
const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1; // 重置到第一页
    getDrawalListFun();
}

// 跳转到指定页
const handleJumpPage = () => {
    const page = parseInt(jumpPage.value);
    const totalPages = Math.ceil(total.value / pageSize.value);
    
    if (isNaN(page) || page < 1) {
        ElMessage.warning('请输入有效的页码');
        jumpPage.value = currentPage.value;
        return;
    }
    
    if (page > totalPages) {
        ElMessage.warning(`页码不能超过总页数 ${totalPages}`);
        jumpPage.value = currentPage.value;
        return;
    }
    
    currentPage.value = page;
    getDrawalListFun();
}

onMounted(() => {
    getDrawalListFun();
});
</script>

<style scoped>
/* 样式保持不变 */
.right{
    width: 187px;
    height: 39px;
    float: right;
    margin-top: -40px;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
}
.right .el-avatar--icon{
    width: 42px;
    height: 35px;
}
.search{
    display: flex;
}
.search .el-input{
    width: 250px;
    height: 30px;
    margin-top: 20px;
}
.search .el-select{
    width: 250px;
    height: 30px;
    margin-top: 20px;
    margin-left: 20px;
}
.search .el-button{
    width: 60px;
    height:30px ;
    margin-top: 20px;
    margin-left: 20px;
}
.log-table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
    margin-top: 13px;
    color: #606266;
}
.log-table th, .log-table td {
    border: 1px solid #ccc;
    padding: 16px 20px;
    text-align: left;
    font-size:16px;
}
.el-overlay{
    height: 500px;
}
img{
    width: 127px;
    height: 75px;
    margin-left: 21px;
}
.log-table th {
    background-color: #f2f2f2;
}
.log-table th:nth-child(1),
.log-table th:nth-child(2),
.log-table th:nth-child(3),
.log-table th:nth-child(5) {
    width: 15%;
    font-size:20px;
}
.log-table th:nth-child(4) {
    width: 50%; 
    font-size: 20px;
}
.upload-demo {
    display: inline-block;
}
.upload-plus {
    width: 120px;
    height: 80px;
    border: 1px dashed #dcdcdc;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}
.plus-icon {
    font-size: 24px;
    color: #999;
}
.plus-text {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
}
.uploaded-image {
    position: relative;
    width: 120px;
    height: 80px;
}
.uploaded-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 4px;
}
.remove-icon {
    position: absolute;
    top: -10px;
    right: -10px;
    background-color: #fff;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
}
.footer{
    width: 600px;
    height: 36px;
    float: right;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
}
.footer .el-button--primary{
    background-color: #fff;
    color: #333;
}
.footer .el-pager{
    font-size: 15px;
}
.footer .btn{
    width: 38px;
    height: 20px;
    border: 1px solid #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>